package jp.tuyano.sample.server;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import jp.tuyano.sample.client.form.SSForm;
import jp.tuyano.sample.client.spreadsheet.ConnectSpreadSheetService;

import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetQuery;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.ServiceException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ConnectSpreaSheetServiceImpl extends RemoteServiceServlet
        implements ConnectSpreadSheetService {

    private static final long serialVersionUID = 1L;

    public String connect(SSForm form) {

        // ユーザー名（Googleアカウントのメールアドレス）を取得
        String userName = form.getUserName();
        // パスワードを取得
        String password = form.getPassword();

        // 認証
        SpreadsheetService sss = new SSServiceCreator(
                "vantel.co.jp-gaesample-1").create(userName, password);

        if (sss == null) {
            return "認証に失敗しました。\n" +
                    "メールアドレスおよびパスワードを確認してください。";
        }

        // 検索対象のスプレッドシートを取得
        FeedURLFactory urlFactory = FeedURLFactory.getDefault();
        SpreadsheetQuery spreadsheetQuery = new SpreadsheetQuery(urlFactory
                .getSpreadsheetsFeedUrl());
        spreadsheetQuery.setTitleQuery(form.getSheetName()); // 検索対象のスプレッドシート名を指定している
        SpreadsheetFeed spreadsheetFeed = null;
        try {
            spreadsheetFeed = sss.query(spreadsheetQuery,
                    SpreadsheetFeed.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServiceException e) {
            throw new RuntimeException(e);
        }
        if (spreadsheetFeed.getEntries().size() == 0) {
            return "スプレッドシートが見つかりません。\n" +
                    "シート名を確認してください。";
        }

        // スプレッドシートを取得
        SpreadsheetEntry spreadsheetEntry = spreadsheetFeed.getEntries().get(0);
        // スプレッドシート名を表示
        System.out.println("名前：" + spreadsheetEntry.getTitle().getPlainText());

        // 検索対象のワークシートを取得
        WorksheetEntry worksheetEntry;
        try {
            worksheetEntry = spreadsheetEntry.getDefaultWorksheet();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServiceException e) {
            throw new RuntimeException(e);
        }

        // ワークシート内を検索
        URL feedUrl = worksheetEntry.getListFeedUrl();

        ListFeed listFeed;
        try {
            listFeed = sss.getFeed(feedUrl, ListFeed.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServiceException e) {
            throw new RuntimeException(e);
        }
        List<ListEntry> listEnties = listFeed.getEntries();
        StringBuilder rsBuilder = new StringBuilder();
        for (ListEntry entry: listEnties) {
            rsBuilder.append(entry.getPlainTextContent()).append("\n");
            System.out.println(entry.getPlainTextContent());
        }
        return rsBuilder.toString();
    }
}
